package com.test.webdemo.servlet;

import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TrackableDispatcherServlet extends DispatcherServlet {
    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        RequestTracker.logStep("2. DispatcherServlet.doDispatch()开始");

        try {
            long start = System.currentTimeMillis();

            // 记录原始请求信息
            RequestTracker.log("请求方法: " + request.getMethod());
            RequestTracker.log("请求URL: " + request.getRequestURL());
            RequestTracker.log("Content-Type: " + request.getContentType());

            super.doDispatch(request, response);

            RequestTracker.logStep("11. DispatcherServlet.doDispatch()完成 - 耗时: "
                    + (System.currentTimeMillis() - start) + "ms");
        } catch (Exception ex) {
            RequestTracker.log("DispatcherServlet处理异常: " + ex.getClass().getName());
            throw ex;
        }
    }

    @Override
    protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        HandlerExecutionChain handler = super.getHandler(request);
        if (handler != null) {
            RequestTracker.logStep("3. 获取到HandlerExecutionChain");
            RequestTracker.log("Handler类型: " + handler.getHandler().getClass().getName());
        } else {
            RequestTracker.logStep("3. 未找到匹配的Handler");
        }
        return handler;
    }
}
